package com.quanyan.common.banner;

import org.springframework.core.env.Environment;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintStream;

/**
 * @author songzj
 * @date 16/4/16-10:26
 */
public class ImageToAscii{

    private final static char[] asc = { ' ', '`', '.', '^', ',', ':', '~', '"', '<', '!', 'c', 't', '+', '{', 'i', '7',
            '?', 'u', '3', '0', 'p', 'w', '4', 'A', '8', 'D', 'X', '%', '#', 'H', 'W', 'M' };

    public static StringBuilder imageToAscii(BufferedImage image) throws IOException {
        StringBuilder sb = new StringBuilder();
        int width = image.getWidth();
        int height = image.getHeight();
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int rgb = image.getRGB(j, i);
                int R = (rgb & 0xff0000) >> 16;
                int G = (rgb & 0x00ff00) >> 8;
                int B = rgb & 0x0000ff;
                int gray = (R * 30 + G * 59 + B * 11 + 50) / 100;
                int index = 31 * gray / 255;
                sb.append(asc[index]);
            }
            sb.append("\n");
        }
        return sb;
    }

    public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
        String location = environment.getProperty("richbanner.location", "banner.png");
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(ImageToAscii.class.getClassLoader().getResourceAsStream("banner.png"));
            StringBuilder builder = imageToAscii(bufferedImage);
            printStream.print(builder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) throws Exception{
//        BufferedImage bufferedImage = ImageIO.read(ImageToAscii.class.getClassLoader().getResourceAsStream("banner.png"));
//        StringBuilder builder = imageToAscii(bufferedImage);
//        System.out.println(builder.toString());
//    }


}
